package com.swust.controller;

import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.swust.pojo.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

//@Controller
@RestController
public class UserController {

    @RequestMapping("/j1")
//    @ResponseBody//他就不会走视图解析器，会直接返回一个字符串
    public String json1() throws JsonProcessingException {

        // jackson,objectMapper
        ObjectMapper mapper = new ObjectMapper();

        User user = new User("张三", 3, "男");

        String str = mapper.writeValueAsString(user);
        return str;
    }

    @RequestMapping("/j2")
    public String json2() throws JsonProcessingException {

        // jackson,objectMapper
        ObjectMapper mapper = new ObjectMapper();

        ArrayList<User> userList = new ArrayList<>();

        User user1 = new User("张三1", 3, "男");
        User user2 = new User("张三2", 3, "男");
        User user3 = new User("张三3", 3, "男");
        User user4 = new User("张三4", 3, "男");

        userList.add(user1);
        userList.add(user2);
        userList.add(user3);
        userList.add(user4);

        String str = mapper.writeValueAsString(userList);
        return str;
    }

    @RequestMapping("/j3")
    public String json3() throws JsonProcessingException {

        // jackson,objectMapper
        ObjectMapper mapper = new ObjectMapper();

        Date date = new Date();

        SimpleDateFormat sdf = new SimpleDateFormat("yy-MM-dd HH:mm:ss");

        return mapper.writeValueAsString(sdf.format(date));
    }
    @RequestMapping("/j4")
    public String json4() throws JsonProcessingException {

        ArrayList<User> userList = new ArrayList<>();
        User user1 = new User("张三1", 3, "男");
        User user2 = new User("张三2", 3, "男");
        User user3 = new User("张三3", 3, "男");
        User user4 = new User("张三4", 3, "男");
        userList.add(user1);
        userList.add(user2);
        userList.add(user3);
        userList.add(user4);

        String s = JSON.toJSONString(userList);

        return s;
    }
}
